package com.youlai.boot.system.excel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.common.excel.ExcelDataHandler;
import com.youlai.boot.common.excel.ExcelHandlerType;
import com.youlai.boot.common.result.ExcelResult;
import com.youlai.boot.system.converter.ProductsingleConverter;
import com.youlai.boot.system.model.dto.ProductsingleExcelDTO;
import com.youlai.boot.system.model.entity.Productsingle;
import com.youlai.boot.system.model.query.ProductsingleQuery;
import com.youlai.boot.system.service.ProductsingleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 单品跟进数据Excel处理器
 *
 * @author Jason
 * @since 2025/6/2
 */
@Component
@ExcelHandlerType("productsingle")
@RequiredArgsConstructor
@Slf4j
public class ProductsingleExcelHandler implements ExcelDataHandler<ProductsingleExcelDTO> {

    private final ProductsingleService productsingleService;
    private final ProductsingleConverter productsingleConverter;

    @Override
    public Class<ProductsingleExcelDTO> getEntityClass() {
        return ProductsingleExcelDTO.class;
    }

    @Override
    public String getFileName() {
        return "单品跟进数据";
    }

    @Override
    public String getSheetName() {
        return "单品跟进数据";
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<ProductsingleExcelDTO> getExportData(Object query) {
        List<Productsingle> productsingleList;
        LambdaQueryWrapper<Productsingle> queryWrapper = new LambdaQueryWrapper<>();
        
        // 指定要查询的字段，排除不需要的字段
        queryWrapper.select(Productsingle.class, tableFieldInfo -> 
            !"create_time".equals(tableFieldInfo.getColumn()) && 
            !"update_time".equals(tableFieldInfo.getColumn()) &&
            !"create_by".equals(tableFieldInfo.getColumn()) &&
            !"update_by".equals(tableFieldInfo.getColumn()) &&
            !"is_deleted".equals(tableFieldInfo.getColumn())
        );
        
        if (query instanceof Map) {
            // 处理Map类型的查询参数
            Map<String, Object> params = (Map<String, Object>) query;
            
            // 添加条件
            if (params.containsKey("startTime")) {
                queryWrapper.ge(Productsingle::getTime, params.get("startTime"));
            }
            if (params.containsKey("endTime")) {
                queryWrapper.le(Productsingle::getTime, params.get("endTime"));
            }
            if (params.containsKey("sku") && StringUtils.hasText((String) params.get("sku"))) {
                queryWrapper.like(Productsingle::getSku, params.get("sku"));
            }
            if (params.containsKey("brand") && StringUtils.hasText((String) params.get("brand"))) {
                queryWrapper.like(Productsingle::getBrand, params.get("brand"));
            }
            if (params.containsKey("categoryLevel3") && StringUtils.hasText((String) params.get("categoryLevel3"))) {
                queryWrapper.like(Productsingle::getCategoryLevel3, params.get("categoryLevel3"));
            }
            if (params.containsKey("shopShortName") && StringUtils.hasText((String) params.get("shopShortName"))) {
                queryWrapper.like(Productsingle::getShopShortName, params.get("shopShortName"));
            }
        } else if (query instanceof ProductsingleQuery pageQuery) {
            // 处理ProductsingleQuery类型的查询参数
            if (pageQuery.getTime() != null && !pageQuery.getTime().isEmpty() && pageQuery.getTime().size() == 2) {
                queryWrapper.ge(Productsingle::getTime, pageQuery.getTime().get(0));
                queryWrapper.le(Productsingle::getTime, pageQuery.getTime().get(1));
            }
            if (StringUtils.hasText(pageQuery.getSku())) {
                queryWrapper.like(Productsingle::getSku, pageQuery.getSku());
            }
            if (StringUtils.hasText(pageQuery.getBrand())) {
                queryWrapper.like(Productsingle::getBrand, pageQuery.getBrand());
            }
            if (StringUtils.hasText(pageQuery.getCategoryLevel3())) {
                queryWrapper.like(Productsingle::getCategoryLevel3, pageQuery.getCategoryLevel3());
            }
            if (StringUtils.hasText(pageQuery.getShopShortName())) {
                queryWrapper.like(Productsingle::getShopShortName, pageQuery.getShopShortName());
            }
        }
        
        // 获取数据列表（不分页）
        productsingleList = productsingleService.list(queryWrapper);
        
        // 转换为Excel数据模型
        return productsingleConverter.entity2ExcelDTO(productsingleList);
    }

    @Override
    public void handleImportData(List<ProductsingleExcelDTO> dataList, ExcelResult result) {
        log.info("开始导入单品跟进数据，共{}条记录", dataList.size());
        
        // 数据校验和处理
        for (ProductsingleExcelDTO dto : dataList) {
            try {
                // 数据验证
                validateData(dto);
                
                // 转换为实体
                Productsingle productsingle = productsingleConverter.excelDTO2Entity(dto);
                log.debug("转换后的实体数据: {}", productsingle);
                
                // 保存到数据库
                boolean saved = productsingleService.save(productsingle);
                if (saved) {
                    // 成功计数
                    result.setValidCount(result.getValidCount() + 1);
                    log.debug("成功保存第{}条数据", result.getValidCount());
                } else {
                    // 失败计数和错误信息
                    result.setInvalidCount(result.getInvalidCount() + 1);
                    String errorMsg = "第" + (result.getValidCount() + result.getInvalidCount()) + "行: 保存失败";
                    result.addErrorMsg(errorMsg);
                    log.error(errorMsg);
                }
            } catch (Exception e) {
                // 失败计数和错误信息
                result.setInvalidCount(result.getInvalidCount() + 1);
                String errorMsg = "第" + (result.getValidCount() + result.getInvalidCount()) + "行: " + e.getMessage();
                result.addErrorMsg(errorMsg);
                log.error("导入单品跟进数据错误: {}", errorMsg, e);
            }
        }
        
        // 设置导入结果
        result.setSuccess(result.getInvalidCount() == 0);
        log.info("单品跟进数据导入完成，成功{}条，失败{}条", result.getValidCount(), result.getInvalidCount());
    }
    
    /**
     * 数据验证
     *
     * @param dto 数据对象
     */
    private void validateData(ProductsingleExcelDTO dto) {
        // 商品名称必填
        if (!StringUtils.hasText(dto.getProductName())) {
            throw new IllegalArgumentException("商品名称不能为空");
        }
        
        // SKU必填
        if (!StringUtils.hasText(dto.getSku())) {
            throw new IllegalArgumentException("SKU不能为空");
        }
        
        // 品牌必填
        if (!StringUtils.hasText(dto.getBrand())) {
            throw new IllegalArgumentException("品牌不能为空");
        }
        
        // 其他业务验证规则
        // ...
    }
    
    @Override
    public List<ProductsingleExcelDTO> getTemplateData() {
        // 返回模板数据（空或示例数据）
        return List.of();
    }
} 